<template>
    <div class="RiskReleaseAdd">
        <div class="jbxx" v-if="showList">
            <van-form ref="validateForm" validate-firstm :readonly="disabled">
                <van-field v-if="cityLevel == '市' && $parent.status == 'add'" required true clickable name="picker"
                    label="是否与省级风险关联" :value="formData.switchGL | inUseName(Enum.SF)" placeholder=" "
                    @click="Enum.IS = true" />
                <van-popup v-model="Enum.IS" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="Enum.SF" value-key="name" @confirm="onConfirm3"
                        @cancel="Enum.IS = false" />
                </van-popup>
                <van-field required true label="风险名称" name="taskName" v-model="formData.taskName" placeholder="请输入风险名称"
                    :rules="rules">
                    <template v-if="formData.switchGL == 0">
                        <van-button :disabled="disabled" slot="button" type="info" size="small"
                            @click="showList = false">检索</van-button>
                    </template>
                    <template v-else>
                        <van-button :disabled="disabled" slot="button" type="info" size="small" @click="showList = false"
                            style="margin-right: 10px;">关联</van-button>
                        <van-button :disabled="disabled" slot="button" type="info" size="small"
                            @click="see()">查看</van-button>
                    </template>

                </van-field>
                <van-field required true label="风险编号" name="taskNo" v-model="formData.taskNo" v-if="formData.taskNo"
                    placeholder=" " />
                <van-field required true clickable readonly name="picker" :value="formData.riskLevel | inUseName(Enum.FXDJ)"
                    label="风险级别" :rules="rules" placeholder="请选择风险级别" @click="disabled ? '' : Enum.ISFXDJ = true" />
                <van-popup v-model="Enum.ISFXDJ" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="Enum.FXDJ" value-key="name" @confirm="onConfirm1"
                        @cancel="Enum.ISFXDJ = false" />
                </van-popup>
                <van-field required true label="发布单位" name="issueUnit" v-model="formData.issueUnit" placeholder="请输入发布单位"
                    :rules="rules" />
                <van-field required true clickable readonly name="datetimePicker" :value="formData.deadline" label="风险上报截止时间"
                    :rules="rules" placeholder="请选择风险上报截止时间" @click="disabled ? '' : showPickerq = true" />
                <van-popup v-model="showPickerq" position="bottom">
                    <van-datetime-picker :min-date="minDate" v-model="currentDate" type="date" title="选择年月日" @cancel="showPickerq = false"
                        @confirm="onConfirmRQ" />
                </van-popup>
                <van-field required true clickable readonly name="signType"
                    :value="formData.signType | inUseName(Enum.FBFS)" label="风险发布方式" :rules="rules"
                    placeholder="请选择风险发布方式" />
                <van-popup v-model="Enum.ISFBFS" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="Enum.FBFS" value-key="name" @confirm="onConfirm2"
                        @cancel="Enum.ISFBFS = false" />
                </van-popup>
                <van-field required readonly label="风险发布人" name="taskCreatePersonName"
                    v-model="formData.taskCreatePersonName" />
                <van-field required readonly label="风险发布时间" name="createDate" v-model="formData.createDate" />
            </van-form>
            <p class="subTitle">风险处置要求</p>
            <van-form :readonly="disabled">
                <van-field label="疑似危房" name="manageDanger" type="textarea" rows="2" autosize
                    v-model="formData.manageDanger" placeholder="请输入" />
                <van-field label="治理中的C级、D级危房" name="manageCD" type="textarea" rows="2" autosize v-model="formData.manageCD"
                    placeholder="请输入" />
                <van-field label="采取管理措施的危房" name="manageCrue" type="textarea" rows="2" autosize
                    v-model="formData.manageCrue" placeholder="请输入" />
            </van-form>
            <template v-if="disabled && $parent.status == 'sign'">

            </template>
            <template v-else>
                <p class="subTitle">风险签收区域</p>
                <div class="singe" v-show="isShowQY">
                    <p class="name">统计区域：</p>
                    <van-radio-group :disabled="disabled" v-model="form.checkedCities1" @change="handleClickTJQY">
                        <van-radio v-for="(item, index) in Enum.TJQY" :key="index"
                            :name="item.enumvalue + '/' + item.enumname">{{ item.enumname }}</van-radio>
                    </van-radio-group>
                </div>
                <div class="singe" v-show="isShowQX">
                    <p class="name">统计区县：</p>
                    <van-checkbox-group :disabled="disabled" v-model="form.checkedCities2" @change="handleClickTJQX">
                        <van-checkbox v-for="(item, index) in Enum.TJQX" :key="index"
                            :name="item.enumvalue + '/' + item.enumname">{{ item.enumname }}</van-checkbox>
                    </van-checkbox-group>
                </div>
                <div class="singe">
                    <p class="name">风险签收区域清单:</p>
                    <van-tag :key="tag" v-for="(tag, index) in dynamicTags" plain color="#409EFF" :closeable="!disabled"
                        :disable-transitions="false" @close="handleClose(index)">
                        {{ tag.enumname }}
                    </van-tag>
                </div>
            </template>
            <div style="margin: 16px;" v-if="!disabled">
                <van-button block type="info" @click="save()">确定</van-button>
            </div>
        </div>
        <template v-else>
            <retrieval @close="close" @retrievalSure="retrievalSure" :type="retType"></retrieval>
        </template>
        <van-popup class="popupDialog" closeable v-model="show3">
            <div class="dialog-title-text">查看</div>
            <div style="width:100%;height:60vh;overflow: scroll;">
                <risk-release-add :disabled="true" :rowData="relationForm" :cityLevel="cityLevel"></risk-release-add>
            </div>
        </van-popup>
    </div>
</template>
<script>
import axios from "axios";
import dd from 'gdt-jsapi'
import Retrieval from "./children/Retrieval" //风险关联
import seeOpinion from "./children/seeOpinion" //查看下级关联风险
import RiskReleaseAdd from './RiskReleaseAdd.vue'
export default {
    name: 'RiskReleaseAdd',
    data() {
        return {
            BaseUrl: window.g.BaseURL,
            showList: true,
            show3: false,
            isShowQY: false,
            isShowQX: false,
            minDate: new Date(),
            currentDate: new Date(),
            showPickerq: false,
            status: "",
            rules: [{ required: true, message: ' ' }],
            formData: {
                cityCode: window.localStorage.getItem("citycode"),
                switchGL: "0",
                signType: "人工发布",
                taskCreatePersonName: JSON.parse(window.localStorage.getItem('userName')).userName,
                taskCreatePersonId: "",
                createDate: "",
            },
            form: {
                checkedCities1: "",
                checkedCities2: [],
            },
            Enum: {
                TJQY: [],
                TJQX: [],
                ISFXDJ: false,
                FXDJ: [
                    {
                        name: 'Ⅰ级',
                        value: 0
                    },
                    {
                        name: 'Ⅱ级',
                        value: 1
                    },
                    {
                        name: 'Ⅲ级',
                        value: 2
                    },
                    {
                        name: 'Ⅳ级',
                        value: 3
                    },
                    {
                        name: 'Ⅴ级',
                        value: 4
                    }
                ],
                IS: false,
                SF: [
                    {
                        name: '是',
                        value: 1
                    },
                    {
                        name: '否',
                        value: 0
                    }
                ],
                ISFBFS: false,
                FBFS: [
                    {
                        name: '人工发布',
                        value: '人工发布'
                    },
                    {
                        name: '智能发布',
                        value: '智能发布'
                    }
                ],
            },
            relationForm: {},
            dynamicTags: [],
        }
    },
    components: {
        Retrieval,
        seeOpinion
    },
    watch: {
        rowData() {
            if (this.rowData) {
                for (var i in this.rowData) {
                    this.$set(this.formData, i, this.rowData[i])
                }
            }
        }
    },
    props: {
        rowData: Object,
        disabled: Boolean,
        cityLevel: String,
    },
    filters: {
        inUseName: function (msg, data) {
            let name = ''
            data.forEach(item => {
                if (item.value == msg) {
                    name = item.name
                }
            })
            return name
        },
    },
    methods: {
        onConfirm(value) {
            this.formData.switchGL = value.value;
            this.Enum.IS = false;
        },
        onConfirm1(value) {
            this.formData.riskLevel = value.value;
            this.Enum.ISFXDJ = false;
        },
        onConfirm2(value) {
            this.formData.signType = value.value;
            this.Enum.ISFBFS = false;
        },
        onConfirm3(value) {
            this.formData.switchGL = value.value;
            this.Enum.IS = false;
        },
        onConfirmRQ(val) {
            let year = val.getFullYear();
            let month = val.getMonth() + 1;
            let day = val.getDate();
            let hour = new Date().getHours();
            let minute = new Date().getMinutes();
            let seconds = new Date().getSeconds();
            if (month >= 1 && month <= 9) {
                month = `0${month}`;
            }
            if (day >= 1 && day <= 9) {
                day = `0${day}`;
            }
            if (hour >= 0 && hour <= 9) {
                hour = `0${hour}`;
            }
            if (minute >= 0 && minute <= 9) {
                minute = `0${minute}`;
            }
            if (seconds >= 0 && seconds <= 9) {
                seconds = `0${seconds}`;
            }
            this.className = "timeClass";
            // this.formData.deadline = `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
            this.formData.deadline = `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
            this.showPickerq = false;
        },
        //保存
        save: async function () {
            this.$refs.validateForm.validate().then(() => {
                if (this.dynamicTags.length == 0) {
                    this.$toast.fail("请选择风险签收区域清单")
                } else {
                    this.$emit('save', true)
                    let url = '/api/farmerHouse/housePreventTaskInfo/signTask';
                    this.formData["cityCodes"] = [];
                    this.dynamicTags.forEach(item => {
                        this.formData["cityCodes"].push(item.enumvalue);
                    })
                    let data = JSON.parse(JSON.stringify(this.formData));
                    delete data.switchGL;
                    axios.post(this.BaseUrl + url, this.formData, {
                        headers: {
                            isOutParam: true,
                        },
                    }).then(webResult => {
                        if (webResult.data.data) {
                            this.$toast.success("保存成功")
                            setTimeout(() => {
                                this.$parent.backHomepage()
                            }, 500)
                            if (window.g.SendMessage) {
                                this.sendInfo()
                            }
                        } else {
                            this.$toast.fail(webResult.data.msg);
                        }
                    });

                }
            }).catch(() => {
                return false;
            })
        },
        //浙政钉消息推送
        sendInfo() {
            let codeData = [];
            this.formData["cityCodes"].forEach(item => {
                let code = item.toString().substring(0, 4);
                let data = codeData.filter(element => {
                    return element.cityCode == code
                })
                if (data.length == 0) {
                    codeData.push({
                        cityCode: item == 330112000000 ? item : code,
                        params: [item]
                    })
                } else if (item == 330112000000) {
                    codeData.push({
                        cityCode: item,
                        params: [item]
                    })
                } else {
                    data[0].params.push(item)
                }
            })
            codeData.forEach((item, index) => {
                let p = null;
                if (this.cityLevel == "省" || !this.cityLevel) {
                    p = new Promise((resolve, reject) => {
                        axios.post(`${this.BaseUrl}/api/farmerHouse/proxy/data/v2`, {
                            "accessCode": "fd77d420365611eeae7f2cf05de0e487",
                            "appKey": "",
                            "cityCode": item.cityCode.length == 4 ? item.cityCode + '00000000' : item.cityCode,
                            "params": { "cityCodes": item.params.join(',') }
                        }, {
                            headers: {
                                isOutParam: true,
                            },
                        }).then(res => {
                            if (res.data.data) {
                                resolve({
                                    level: '省',
                                    data: res.data.data
                                })
                            }
                        })
                    })
                } else if (index == 0) {
                    p = new Promise((resolve, reject) => {
                        axios.get(`${window.g.BaseURL5}/user/getUser?cityCodes=${this.formData["cityCodes"]}`,
                            {
                                headers: {
                                    "isOutParam": true,
                                    "isOutParamS": true
                                }

                            }).then(res => {
                                resolve({
                                    level: '市',
                                    data: res.data.data
                                })
                            })
                    })
                }
                p.then((res) => {
                    let str = `${this.formData.issueUnit}发布了${this.formData.taskName}风险，请及时通过“粤政易”系统-农房安全-防汛 防台模块签收处置！！`
                    let arr = []
                    let params = null;
                    if (res.level == '省') {
                        params = eval('(' + res.data + ')')
                        params.data.forEach(item => {
                            arr.push(item.ST_LOGINNAME)
                        })
                    } else {
                        res.data.forEach(item => {
                            arr.push(item.ST_LOGINNAME)
                        })
                    }
                    if (arr.length > 0) {
                        let data = {
                            "bizMsgId": "9689ec95-1203-ab3e-7e56-b04d886ca435",
                            "appKey": "6738b790-69e8-11ec-a673-6805cab640a0",
                            "userNames": arr.join(','),
                            "msg": JSON.stringify({ "msgtype": "text", "text": { "conten": str } }),
                            "token": null
                        }
                        axios.post(`${this.BaseUrl}/api/farmerHouse/selfDingDing/dTalkWorkNoticeNetNfBiz/v2`, data, {
                            headers: {
                                isOutParam: true,
                            },
                        }).then(resp => {
                            console.log(resp)
                        })
                    }
                })
            })
        },
        // 查看
        see() {
            if (this.relationForm.taskNo) {
                this.show3 = true;
            } else {
                this.$toast.fail("请先检索关联后查看")
            }
        },
        // 关闭
        close() {
            this.showList = true
        },
        // 关联框确定
        retrievalSure(data) {
            this.relationForm = data;
            this.$set(this.formData, 'taskName', data.taskName);
            this.$set(this.formData, 'taskNo', data.taskNo);
            this.$set(this.formData, 'relationTaskNo', data.taskNo);
            this.$set(this.formData, 'relationName', data.taskNo);
            this.showList = true
        },
        // 区域选择
        handleClickTJQY(val) {
            this.Enum.TJQX = [];
            this.isShowQX = true;
            this.form.checkedCities2 = [];
            this.getCitesData(val.split("/")[0], this.Enum.TJQX)
            // 避免重复添加
            let data = this.dynamicTags.filter(item => { return item.enumvalue == val.split("/")[0] });
            data.length == 0 ? this.dynamicTags.push({
                enumname: val.split("/")[1],
                enumvalue: val.split("/")[0]
            }) : ""
        },
        //区县选择
        handleClickTJQX(vals) {
            let val = vals.at(-1)
            let data = this.dynamicTags.filter(item => { return item.enumvalue == val.split("/")[0] });
            data.length == 0 ? this.dynamicTags.push({
                enumname: (this.form.checkedCities1 ? this.form.checkedCities1.split("/")[1] + "/" : '') + val.split("/")[1],
                enumvalue: val.split("/")[0]
            }) : ""
        },
        // 删除标签
        handleClose(index) {
            this.dynamicTags.splice(index, 1);
        },
        getCitesData(code, child) {
            let self = this
            axios.get(this.BaseUrl + "/api/rescatalog/gsaCodeCity/listForTree/" + code, {
                headers: {
                    isOutParam: true,
                }
            }).then(response => {
                if (response.data.data) {
                    const citiesData = response.data.data;
                    function checkCities(children) {
                        children.forEach(c => {
                            if (c.children && c.children.length === 0) {
                                delete c["children"];
                            } else if (c.children) {
                                checkCities(c.children);
                            }
                        });
                    }
                    checkCities(citiesData);
                    citiesData.forEach(item => {
                        child.push({
                            enumname: item.cityname,
                            enumvalue: item.citycode
                        })
                    })
                } else {
                    self.$message.error("获取行政区划数据出错");
                    console.error("获取行政区划数据出错", response);
                }
            })
        },
    },
    mounted() {
        this.formData.createDate = this.getDate();
        if (this.rowData) {
            this.dynamicTags = []
            for (var i in this.rowData) {
                if (i == 'signArea' && this.rowData[i]) {
                    let signArea = this.rowData[i].split(",");
                    signArea.forEach(item => {
                        this.dynamicTags.push({
                            enumname: item,
                            enumvalue: item
                        })
                    })
                } else {
                    this.$set(this.formData, i, this.rowData[i])
                }

            }
        }
        let citycode = window.localStorage.getItem("citycode");
        if (this.cityLevel == "省" || !this.cityLevel) {
            this.isShowQY = true;
            this.getCitesData(330000000000, this.Enum.TJQY)
            this.isShowQX = false;
        } else if (this.cityLevel == "市") {
            this.isShowQY = false;
            this.form.checkedCities1 = "";
            this.getCitesData(citycode, this.Enum.TJQX)
            this.isShowQX = true;
        }
        dd.ready(() => {
            dd.setTitle({
                title: "详情信息",
            }).then((res) => {

            }).catch((err) => {
                console.error(err)
            })
        })


    }
}
</script>
<style lang="scss">
.RiskReleaseAdd {
    .subTitle {
        width: 100%;
        height: 40px;
        line-height: 40px;
        font-weight: bold;
        padding-left: 10px;
        font-size: 16px;
        color: #000;
    }

    .jbxx {

        .van-field__label,
        .van-radio__label,
        .van-checkbox__label {
            color: #000;
            font-size: 14px;
        }
    }

    .singe {
        .name {
            line-height: 40px;
            font-size: 14px;
            padding-left: 10px;
            color: #000;
        }
    }

    .popupDialog {
        width: 300px;
        border-radius: 11px;
        background-color: #fff;

        .dialog-title-text {
            line-height: 40px;
            text-align: center;
            border-bottom: 1px solid #ccc;
        }

        .buttonfooter {
            padding: 10px;
            margin-top: 4px;
            display: flex;
            justify-content: space-between;

            .van-button {
                width: 47%;
            }
        }
    }
}
</style>
<style lang="scss">
.RiskReleaseAdd {
    .van-field__control {
        text-align: right !important;
    }

    .van-field__label {
        width: auto !important;
    }

    .van-radio-group,
    .van-checkbox-group {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap
    }

    .van-radio,
    .van-checkbox {
        margin: 10px;
    }

    .van-tag {
        padding: 10px;
        margin: 10px;
    }

    .popupDialog {
        width: 300px;
        border-radius: 11px;
        background-color: #fff;

        .dialog-title-text {
            line-height: 40px;
            text-align: center;
            border-bottom: 1px solid #ccc;
        }

        .van-field__control {
            text-align: right !important;
        }

        .buttonfooter {
            padding: 10px;
            margin-top: 4px;
            display: flex;
            justify-content: space-between;

            .van-button {
                width: 47%;
            }
        }
    }
}
</style>
